<?php
/*
	平台后台管理员 角色权限 相关模型
*/
namespace admin\models\auth;
use Yii;
use common\models\AuthRule as FxAuthRule;

class AuthRule extends FxAuthRule
{
	//获取单个权限
	public static function getAuthRule($id)
	{
		$data = self::find()->where(['id'=>$id])->asArray()->one();
		return $data;		
	}

	//获取权限
	public static function getAuthRules($where, $type = 0, $order = 'sort ASC'): array
    {
		$data = self::find()->where($where)->orderBy($order)->asArray()->all();
		if($type == 1 || !\Yii::$app->params['apiAuth']) return $data;
		foreach($data as &$val)
		{
			$val['api_paths'] = AuthApi::getAll(['rule_id'=>$val['id']]);
			$val['children'] = $val['api_paths'];
		}
		return $data;
	}

	//获取权限
	public static function getAuthRules2($where, $apiIds = [], $order = 'sort ASC'): array
    {
		$data = self::find()->where($where)->orderBy($order)->asArray()->all();
		if(!\Yii::$app->params['apiAuth']) return $data;

		foreach($data as &$val)
		{
			$where = $apiIds?['and',['rule_id'=>$val['id']],['in','id',$apiIds]]:['rule_id'=>$val['id']];
			$children = AuthApi::getAll($where);
			$val['children'] = $children;
		}
		return $data;
	}


	//获取所权限路由 
	public static function getAllAuth(): array
    {
		$where = ['>','id','0'];
		$data = self::getAuthRules($where);
        return Roles::getTree($data);
	}



	//获取下面所有子菜单
	public static function getChildMenu($pid='0')
	{
		$where = ['>','id','0'];
		$data = self::getAuthRules($where);
        return self::getSubMenu($data,$pid);
	} 


	public static function getSubMenu($menus, $pid = 0,&$list = array(), $level = 0)
	{
		foreach($menus as $menu)
		{
			if($menu['pid'] == $pid){  // && $menu['is_menu']=='1'
				$menu['level'] = $level;
				$menu['api_paths'] = AuthApi::getAllArr(['rule_id'=>$menu['id']]);
//				 var_dump($menu['api_paths']);
				$menu['children'] = $menu['api_paths'];
				$list[] = $menu;
				self::getSubMenu($menus, $menu['id'], $list, $level+1);
			}
		}
		return $list;
	}

}

